package com.meisiabc.app.web.auth;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.jwt.crypto.sign.SignerVerifier;

/**
 * Created by sunchangpeng
 */
@Slf4j
public class JwtAuthHandler extends AuthHandler {
    public static final SignerVerifier signerVerifier = new MacSigner("meisi");

    public static String resolveAuthTokenValue(Authentication authentication) {
        return JwtHelper.encode(JSON.toJSONString(authentication), signerVerifier).getEncoded();
    }

    @Override
    protected boolean processAuthToken(String authToken) {
        Authentication authentication = decodeAndVerify(authToken);
        if (authentication == null) {
            return false;
        }

        SecurityContextHolder.setContext(new SecurityContext(authentication.getMobile(), authentication.getOpenid()));
        return true;
    }

    private Authentication decodeAndVerify(String jwtToken) {
        try {
            Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, signerVerifier);
            return JSON.parseObject(jwt.getClaims(), Authentication.class);
        } catch (Exception e) {
            log.error("decode and verify jwt content error,jwtToken:{}", jwtToken, e);
        }

        return null;
    }
}
